/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.asportoonline.controller;

import java.io.IOException;
import java.util.Iterator;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.asportoonline.context.ResponseAndView;
import org.asportoonline.context.ResponseObject;
/**
 *
 * @author Valerio Costmagna <costamagna.valerio@gmail.com>
 */
public class ViewDispatcher {
    
	protected RequestDispatcher dispatcher ;

	public ViewDispatcher(RequestDispatcher requestDispatcher) {
		dispatcher = requestDispatcher;
	}

	public void forward(HttpServletRequest req, HttpServletResponse res, ResponseAndView responseObject) throws ServletException, IOException {

		mergeDataRequest(req, responseObject.getResponseObject());

		dispatcher.forward(req,res);
	}

	private void mergeDataRequest(HttpServletRequest req, ResponseObject responseObject) {

		if (responseObject == null)
			return;

		for (Iterator listaParams = responseObject.getRequestKeys().iterator(); listaParams.hasNext(); )
		{
			String key = (String) listaParams.next();
			req.setAttribute(key, responseObject.getValue(key));
                        System.out.println("Mappato attributo nella request: "+key+": "+responseObject.getValue(key));
			//logger.debug("Mappato attributo nella request: "+key+": "+responseObject.getValue(key));
		}

		for (Iterator listaParams = responseObject.getSessionKeys().iterator(); listaParams.hasNext(); )
		{
			String key = (String) listaParams.next();
			req.getSession().setAttribute(key, responseObject.getValue(key));
			//logger.debug("Mappato attributo nella session: "+key+": "+responseObject.getValue(key));
		}
	}
}
